package mspbots.cw.client.core.data.subdata;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.client.core.AbstractToolsUtil;
import mspbots.cw.client.core.data.BaseSyncService;
import mspbots.cw.client.core.client.ClientProperties;
import mspbots.cw.common.QueryParams;
import mspbots.cw.common.RabbitKeys;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.common.ResultSync;
import mspbots.cw.common.subdata.SubDataType;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author AlexBob
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class SlasServiceImpl extends AbstractToolsUtil implements BaseSyncService {

    @Override
    public Mono<Void> syncSlow(ClientProperties properties) {
        ResultSync resultSync = ResultSync.withDefault("SLAS-SYNC");
        return this.get(QueryParams.withDefault())
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .contextWrite(ctx -> ctx.put("properties", properties))
                .doOnNext(resultNode -> this.syncResult(resultSync.getRequestId(), properties.getTenantId(),
                        SubDataType.SLAS, resultNode))
                .flatMap(resultNode -> syncSlasPriorities(resultNode.get("id").intValue(), properties))
                .then();
    }

    private Flux<JsonNode> get(QueryParams queryParams) {
        return this.cwWebClient.fetch("/service/slas", queryParams);
    }

    private Mono<Void> syncSlasPriorities(Integer slaId, ClientProperties properties) {
        ResultSync resultSync = ResultSync.withDefault("SLAS-PRIORITY-SYNC");
        return this.getPriority(slaId, QueryParams.withDefault())
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .contextWrite(ctx -> ctx.put("properties", properties))
                .doOnNext(resultNode -> this.syncResult(resultSync.getRequestId(), properties.getTenantId(),
                        SubDataType.SLAS_PRIORITIES, resultNode))
                .then();
    }

    private Flux<JsonNode> getPriority(Integer slaId, QueryParams queryParams) {
        return this.cwWebClient.fetch("/service/slas/" + slaId + "/priorities", queryParams);
    }

    private void syncResult(UUID uuid, Long tenantId, SubDataType dataType, JsonNode resultNode) {
        this.sendEntity(RabbitKeys.SUB_DATA_SYNC_QUEUE_KEY, ResultMsg.builder()
                .requestId(uuid).id(resultNode.get("id").longValue())
                .action(dataType.name()).entity(resultNode).tenantId(tenantId)
                .syncDate(LocalDateTime.now()).build());
    }

}
